package dir

import (
	"context"
	"errors"
	"fmt"
	"os"
	"path"
	"time"
)

func GetIPCIds(folder string) []string {
	resutl := make([]string, 0)
	entrys, err := os.ReadDir(folder)
	if err != nil {
		fmt.Println(err)
		return resutl
	}
	for _, entry := range entrys {
		resutl = append(resutl, entry.Name())
	}
	return resutl
}

type FolderListen struct {
	baseFolder    string
	id            string
	day           string
	uploadHistory bool
}

func FileExists(name string) (bool, error) {
	_, err := os.Stat(name)
	if err == nil {
		return true, nil
	}
	if errors.Is(err, os.ErrNotExist) {
		return false, nil
	}
	return false, err
}
func NewFolderListen(baseFolder, id string) *FolderListen {
	return &FolderListen{
		baseFolder:    baseFolder,
		id:            id,
		day:           TodayString(),
		uploadHistory: false,
	}
}

func (f *FolderListen) Run(ctx context.Context, ch chan string) {
	var n = 0
	m3u8File := path.Join(f.baseFolder, f.id, GetTodayM3u8())
	var first = true
	//m3u8File := path.Join(f.baseFolder, f.id, "20230806.m3u8")

	fmt.Println(f.id, "run")
	dir := path.Join(f.baseFolder, f.id)
	for {
		time.Sleep(time.Second * 5)
		//如果目录不存在，退出
		exist, _ := FileExists(dir)
		//fmt.Println(f.id, "exist", exist)
		if !exist {
			fmt.Println(f.id, "文件夹被删除")
			break
		}

		result, count, err := Increment(m3u8File, n)
		if err != nil {
			continue
		}
		n = count
		if first {
			first = false
			if !f.uploadHistory && count > 10 {
				//第一次启动，前面积压太多 ts，直接跳过
				continue
			}
		}
		if TodayString() != f.day {
			fmt.Println("break run")
			break
		}
		if result != nil && len(result) > 0 {
			for i := range result {
				ch <- path.Join(f.baseFolder, f.id, result[i])
			}
		}
		if ctx.Err() != nil {
			break
		}

	}
}
